<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\circle;

use app\api\model\dao\Circle;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Exception;
use think\Log;
use think\Validate;

class UpdateCircle extends PageBase
{

    private $objCircle;

    public function __construct()
    {
        parent::__construct();

        $this->objCircle = new Circle();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'cir_id' => 'require',
        ];
        $msg = [
            'cir_id.require' => '圈子id不能为空',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
//        $ret = $this->checkToken($param);
//        if (false === $ret) {
//            throw new Exception('check token fail...', Error::ERR_SYS);
//        }

        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_CUSTOM, $ret);
        }

        if (empty($param['briefing']) && empty($param['announcement'])) {
            return $this->getRes(Error::ERR_PARAM);
        }

        // 2、从数据库中获取圈子详情
        $ret = $this->objCircle->getCircleByid($param['cir_id']);
        if (false === $ret) {
            Log::error(__METHOD__ . 'get circle info from db fail. [circle_id: ' . $param['cir_id'] . ']');
            return $this->getRes(Error::ERR_SYS);
        }

        if (empty($ret)) {
            Log::error(__METHOD__ . 'circle is empty. [circle_id: ' . $param['cir_id'] . ']');
            return $this->getRes(Error::ERR_CIRCLE_NOT_EXIST);
        }

        // 3、校验是否被删除
        if (Flag::CONST_CIRCLE_DELETED == $ret['is_delete']) {
            Log::error(__METHOD__ . 'circle is deleted');
            return $this->getRes(Error::ERR_CIRCLE_DELETED);
        }

        // 4、校验是否审核
        if (Flag::CONST_CIRCLE_APPROVE_PASS != $ret['approve_status']) {
            Log::error(__METHOD__ . 'circle is not approve');
            return $this->getRes(Error::ERR_CIRCLE_APPROVE_NOT);
        }

        if (!empty($param['briefing'])) {
            $input['briefing'] = trim($param['briefing']);
        }

        if (!empty($param['announcement'])) {
            $input['announcement'] = trim($param['announcement']);
        }

        $input['id'] = $param['cir_id'];
        $input['update_time'] = time();

        $ret = $this->objCircle->updateCircle($input);
        if (false === $ret) {
            Log::error(__METHOD__ . 'add circle fail. [field: ' . json_encode($input) . ']');
            return $this->getRes(Error::ERR_SYS);
        }

        return $this->getRes();
    }
}
